<!--
 * @Author: 17607638761 2856491026@qq.com
 * @Date: 2023-05-17 13:43:01
 * @LastEditors: 17607638761 2856491026@qq.com
 * @LastEditTime: 2023-06-16 16:57:58
 * @FilePath: \bpm-ui\src\views\middle-platform\unit-ability-overview\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
	<div class="container">
		<div class="head">
			<div class="query-form">
				<yd-form
					v-if="isForm"
					ref="myForm"
					:options="formOptions"
					:model="params.indexDataQuery"
					@change="handlerSelectChange"
					@formInit="handlerFormInit"
					@search="handlerFormInit"
				>
					<template #form-btn="props">
						<div>
							<el-button class="yd-form-btn" type="primary" @click="handleSearchClick(props.model)">查询</el-button>
						</div>
						<span style="font-size: 18px" class="service-call-details" @click="serverRequestDetailsClick">
							<el-icon><MoreFilled /></el-icon>
							<span style="border-bottom: 1px solid #fff; font-weight: 500">服务调用详情</span>
						</span>
					</template>
				</yd-form>
			</div>
		</div>
		<div class="content">
			<div class="side-data">
				<YdCard>
					<div
						v-for="(item, index) in state.sideData"
						:key="item.serviceCode"
						:class="{ active: state.ind == index, data: true }"
						@click="sideDataClick(item, index)"
					>
						{{ item.serviceName }}
					</div>
				</YdCard>
			</div>
			<el-row :key="Math.random() * 100" :gutter="20" class="main">
				<el-col :span="24">
					<div class="small-head">
						<YdCard>
							<div>
								<span>服务调用形式: {{ state.smailHead.title }}</span>
							</div>
							<div>
								<!-- <span v-for="item in state[mode]" :key="item.name">{{ item.name }}: {{ item.value }}</span> -->

								<span v-if="mode === 'ApiOrSdk'">调用量: {{ state.smailHead.reqCount }}次</span>
								<span v-if="mode === 'SaasOrPaas'">核心页面浏览量: {{ state.smailHead.corePageReqCount }}次</span>
								<span v-if="mode === 'H5'">浏览量: {{ state.smailHead.reqCount }}次</span>
								<span v-if="mode === 'SaasOrPaas' || mode === 'H5'">用户数: {{ state.smailHead.userNumber }}个</span>
								<span>使用方数: {{ state.smailHead.userNumbers }}家</span>
							</div>
						</YdCard>
					</div>
				</el-col>
				<el-col :span="24">
					<div :key="Math.random() * 100" class="ability-service ability-service-first">
						<YdCard>
							<div
								:style="{
									display: 'grid',
									gridTemplateColumns: mode === 'SaasOrPaas' ? 40 + '%' + 30 + '%' + 30 + '%' : 40 + '%' + 60 + '%',
									minHeight: 300 + 'px',
								}"
							>
								<div style="width: 100%; height: 100%">
									<YdEcharts :ref-val="'ability-service-first-pie'" :options="state.alarmQuantityStatistcsOptions" />
								</div>
								<div v-if="mode === 'SaasOrPaas'" style="width: 100%; height: 100%">
									<YdEcharts :ref-val="'saas-login-success'" :options="state.saasOrPaasLoginSuccess" />
								</div>
								<div style="padding: 0 20px; border-left: 2px solid; border-color: rgba(255, 255, 255, 0.4)">
									<PurpostComponent :data="state.firstApiData" :isHead="false" :marginTop="33" />
								</div>
							</div>
						</YdCard>
					</div>
				</el-col>
				<el-col :span="12">
					<div class="flow-variation el-card-body-bottom-zero">
						<YdCard :title="'流量变化趋势'">
							<div style="width: 100%; height: 300px">
								<YdEcharts :ref-val="'flow-variation-line'" :options="state.flowVariationOptions" />
							</div>
							<template #yd-card-btn>
								<div style="margin-right: 20px">
									<span
										v-for="(item, index) in state.ydCardBtnGroup"
										:key="item.id"
										:class="{ active: state.ydCardBtnGroupCurrent === index, ydCardBtnGroupClass: true }"
										@click="ydCardBtnGroupClick(item, index)"
									>
										{{ item.name }}
									</span>
								</div>
							</template>
						</YdCard>
					</div>
				</el-col>
				<el-col :span="12">
					<div class="ability-service el-card-body-bottom-zero">
						<YdCard :title="'响应量变化趋势'">
							<div style="width: 100%; height: 300px">
								<YdEcharts :ref-val="'ability-service-line-bar'" :options="state.variationTrend" />
							</div>
						</YdCard>
					</div>
				</el-col>
				<el-col :span="12">
					<div :key="Math.random() * 100" class="call-variation el-card-body-bottom-zero">
						<YdCard :title="echartsData.callVariationTitle">
							<div style="width: 100%; height: 300px">
								<YdEcharts :ref-val="'call-variation-line'" :options="state.callVariationOptions" />
							</div>
						</YdCard>
					</div>
				</el-col>
				<el-col :span="12">
					<div class="response-consuming el-card-body-bottom-zero">
						<YdCard :title="'响应耗时分布'">
							<div style="width: 100%; height: 300px">
								<YdEcharts :ref-val="'response-consuming-bar'" :options="state.responseConsumingOptions" />
							</div>
						</YdCard>
					</div>
				</el-col>
			</el-row>
		</div>
		<MoreDialog ref="moreDialogRef" :data="state.sideDialogData" @handlerMoreClick="handlerMoreClick" />
	</div>
</template>

<script setup lang="ts" name="ability-service-analysis">
import { reactive, ref, onMounted, onBeforeUnmount, computed, nextTick, watch, toRaw, onActivated, onBeforeMount } from 'vue';
import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router';
import { ECOption } from 'echarts';
import 'echarts/lib/component/legend';
import { startTimer } from '@/utils/timer';
import YdEcharts from '@/components/YdEcharts/index.vue';
import AsTemplate from '../as-template.vue';
import MoreDialog from '../moreDialog.vue';
import PurpostComponent from '../purpost-component.vue';
import { queryAbilityServer, queryDataIndicator, queryDataFlow, queryDataResponse } from '@/api/middle-monitor/unit-ability';
import { queryDataByAbilityServer, queryDataResponseTimeDistribution, queryDataReqCountTrend } from '@/api/middle-monitor/ability-server-analysis';
import { dataZoom, SERIESLABEL, SYMBOLSIZE, GRID, TITLE, LEGEND, formatterToolTipFn, NAMETEXTSTYLE } from '../echartsConfig';
import {
	bitRateFormatter,
	calculateTimeBefore,
	commonFormatter,
	getDefaultDate,
	getDefaultLast1hDate,
	parseTime,
	toDecimalFormate,
	toDecimalFormate2,
} from '@/utils/common';
import { publicValue } from '@/api/search/searchOptions';
import { colorSortGroup, xAxisOrYaxis } from '@/utils/echartsConfig';

const route = useRoute();
const router = useRouter();
const echartsData = reactive<any>({
	provincialCompanyData: {
		title: {
			text: '省公司',
			left: 'center',
			textStyle: {
				//文字颜色
				color: '#FFFFFF',
				//字体风格,'normal','italic','oblique'
				fontStyle: 'normal',
				//字体粗细 'normal','bold','bolder','lighter',100 | 200 | 300 | 400...
				fontWeight: 500,
				//字体系列
				fontFamily: 'sans-serif',
				//字体大小
				fontSize: 17,
			},
		},
		// 取消鼠标移入
		silent: true,
		tooltip: {
			trigger: 'item',
		},
		legend: {
			orient: 'horizontal',
			top: 'bottom',
			icon: 'circle',
			align: 'left',
			bottom: '0',
			itemWidth: 12,
			itemHeight: 12,
			textStyle: {
				color: 'red',
				fontSize: 30,
				align: 'left',
				// 文字块背景色，一定要加上，否则对齐不会生效
				backgroundColor: 'transparent',
			},
		},
	},
	alarmQuantityStatistcsData: [
		{
			value: 1048,
			name: '省公司',
		},
		{
			value: 735,
			name: '总公司',
		},
		{
			value: 580,
			name: '专业公司',
		},
		{
			value: 484,
			name: '集团总部',
		},
		{
			value: 484,
			name: '其他',
		},
	],
	data: [2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018],
	barSeriesColor: {
		type: 'liner',
		x: 0,
		y: 1,
		x2: 0,
		y2: 0,
		colorStops: [
			{
				offset: 0,
				color: '#06F4F4',
			},
			{
				offset: 1,
				color: '#1dc69d',
			},
		],
		global: false, // 缺省为 false
	},
	apiSaasPieData: [
		{
			value: 0,
			name: '超时次数',
		},
		{
			value: 0,
			name: '成功次数',
		},
		{
			value: 0,
			name: '客户端失败次数',
		},
		{
			value: 0,
			name: '服务端失败次数',
		},
	],
	// 登录成功率
	saasOrPaasLoginSuccessRate: [
		{
			value: 0,
			name: '告警数占比',
		},
	],
	// 流量变化趋势所有数据
	flowVariationData: {},
	showThatDayFlowVariationData: [], // 今天
	showYesterdayFlowVariationData: [], // 昨天
	showLastWeekFlowVariationData: [], // 上周
	showTimeLapaseData: [], // 流量变化趋势时间x轴刻度
	// xxxx流量变化趋势数据
	soAndso: {
		successCountData: [], // 客户端成功次数
		clientFailCountData: [], // 客户端失败次数
		serverFailCountData: [], // 服务端失败次数
		timeoutCountData: [], // 超时次数
		avgServerResponseCountData: [], // 平均响应耗时变化趋势
		// xxxx变化趋势时间x轴刻度
		timeLapseTrend: [],
	},
	responseTimeDistributionLapset: [], // 响应耗时分布x轴刻度
	responseTimeDistributionData: [], // 响应耗时分布数据

	reqCountTrendTimeLapse: [], // 浏览量x轴刻度
	reqCountTrendTimeData: [], // 浏览量数据

	callVariationTitle: '调用量',
});
const colors = ['#06F4F4', '#FE9A0C', '#814BFB', '#FECE0C', '#57E5BA', '#129ED1', '#FA876B', '#FC64AF', '#D261FC', '#9A54F2'];
const params = reactive({
	// 指标数据接口参数
	indexDataQuery: {
		abilityCode: '',
		serviceCode: '',
		invocationMode: '',
		pageSize: 10,
		pageNum: 1,
		startTime: '',
		endTime: '',
		...route.query,
	},
	// startTime: '2023-06-08 11:46:00',
	// 	endTime: '2023-06-08 12:46:00',
});
let mode = computed(() => {
	let modeName = params.indexDataQuery.invocationMode;
	if (modeName === 'API' || modeName === 'SDK') {
		return 'ApiOrSdk';
	}
	if (modeName === 'SaaS' || modeName === 'PaaS') {
		return 'SaasOrPaas';
	}
	return 'H5';
});
const state = reactive<any>({
	extendData: {},
	providerData: [
		{ label: '能力数', value: '122' },
		{ label: '使用方数', value: '122' },
		{ label: '订购单量', value: '122' },
	],
	userData: [
		{ label: '能力数', value: '122' },
		{ label: '订购单量', value: '122' },
	],
	ind: 0,
	ydCardBtnGroupCurrent: 0,
	sideData: [],
	sideDialogData: [],
	// 能力查询/使用方数、订单量
	abilityServerData: { id: null, abilityCode: '', abilityName: '', outputModeCode: '', serverList: [], userNumber: 0, purchaseOrderNumber: 0 },
	smailHead: {
		title: '',
		purchaseOrderNumber: 0,
		userNumber: 0,
		serverList: [],
	},

	// 响应量饼状图
	alarmQuantityStatistcsOptions: {
		title: { ...TITLE, text: '响应量', top: 'bottom', left: '25%' },
		tooltip: {
			trigger: 'item',
			formatter: '{b} : {c}次',
		},
		legend: {
			// vertical 上下布局
			orient: 'vertical',
			top: 'center',
			x: '70%',
			textStyle: {
				color: '#fff',
				fontSize: 14,
			},
			// itemWidth: 24, // 设置图例图形的宽
			// itemHeight: 18, // 设置图例图形的高
			// itemGap设置各个item之间的间隔，单位px，默认为10，横向布局时为水平间隔，纵向布局时为纵向间隔
			itemGap: 20,
			// 文字靠右
			align: 'left',
		},

		emphasis: {
			label: {
				show: true,
			},
		},
		color: ['#FE9A0C', '#1DC69D', '#FE5578', '#697CF6'],
		series: [
			{
				name: 'Nightingalehart',
				type: 'pie',
				radius: ['40%', '80%'],
				roseType: 'radius',
				// 设置饼状图位置
				center: ['30%', '45%'],
				data: echartsData.apiSaasPieData,
				labelLine: {
					show: false,
				},
				...SERIESLABEL,
			},
		],
	} as ECOption,
	// 登录成功率环状图
	saasOrPaasLoginSuccess: {
		title: {
			text: '登录成功率',
			left: 'center',
			top: 'bottom',
			textStyle: {
				//文字颜色
				color: '#FFFFFF',
				//字体风格,'normal','italic','oblique'
				fontStyle: 'normal',
				//字体粗细 'normal','bold','bolder','lighter',100 | 200 | 300 | 400...
				fontWeight: 500,
				//字体系列
				fontFamily: 'sans-serif',
				//字体大小
				fontSize: 16,
			},
		},
		// 取消鼠标移入
		silent: true,
		tooltip: {
			trigger: 'item',
		},
		// 设置饼状图颜色ss
		color: [colorSortGroup[0], '#57769A'],
		series: [
			{
				name: '登录成功率',
				type: 'pie',
				radius: ['50%', '70%'],
				avoidLabelOverlap: false,
				top: 0,
				label: {
					normal: {
						show: true,
						position: 'center',
						color: '#FFFFFF',
						// 算百分比
						// formatter: '{rate|{d}}{per|%}',
						formatter: '{rate|{c}}{per|%}',
						// 单独设置样式，类似class
						rich: {
							per: {
								fontFamily: '微软雅黑',
								fontSize: 20,
								color: colorSortGroup[0],
							},
							rate: {
								fontFamily: '微软雅黑',
								fontSize: 40,
								color: colorSortGroup[0],
							},
						},
					},
					emphasis: {
						//中间文字显示
						show: true,
					},
				},
				emphasis: {
					label: {
						show: true,
					},
				},
				labelLine: {
					show: false,
				},
				data: echartsData.saasOrPaasLoginSuccessRate,
			},
		],
	} as ECOption,
	// 进度条组件
	firstApiData: [],
	apiOrSdkData: [
		{ label: '系统成功率', type: 1, value: 0, color: colors[3], colorStart: colors[1] },
		{ label: '业务级成功率', type: 1, value: 0, color: colors[4], colorStart: colors[5] },
		{ label: '平均响应耗时', type: 3, value: 0, color: colors[8], colorStart: colors[9], isTime: true },
	],
	saasOrPaasData: [
		// { label: '登录成功率', value: 0, color: colors[4], colorStart: colors[5] },
		{ label: '系统成功率', type: 1, value: 0, color: colors[3], colorStart: colors[1] },
		{ label: '平均响应耗时', type: 3, value: 0, color: colors[8], colorStart: colors[9], isTime: true },
	],
	h5Data: [
		{ label: '系统成功率', type: 1, value: 0, color: colors[3], colorStart: colors[1] },
		{ label: '平均响应耗时', type: 3, value: 0, color: colors[8], colorStart: colors[9], isTime: true },
	],
	// 流量变化趋势折线图
	flowVariationOptions: {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'line',
			},
			formatter: function (params: any) {
				let id: number = state.ydCardBtnGroup[state.ydCardBtnGroupCurrent].id;
				let unit: string;
				switch (id) {
					case 1:
						unit = 'bps';
						break;
					case 2:
						unit = 'B';
						break;
					case 3:
						unit = '个';
						break;
					case 4:
						unit = 'pps';
						break;
					default:
						unit = '个';
				}
				// 自定义 tooltip 数据
				return formatterToolTipFn(params, unit);
			},
		},
		color: colorSortGroup,
		grid: { ...GRID },
		xAxis: {
			...xAxisOrYaxis.xAxis,
			data: echartsData.showTimeLapaseData,
		},
		yAxis: {
			...xAxisOrYaxis.yAxis,
			// 文本颜色
			axisLabel: {
				show: true,
				textStyle: {
					color: '#ffffff',
				},
				formatter: function (value: any) {
					let id: number = state.ydCardBtnGroup[state.ydCardBtnGroupCurrent].id;
					let unit: string;
					switch (id) {
						case 1:
							unit = 'bps';
							break;
						case 2:
							unit = 'B';
							break;
						case 3:
							unit = '个';
							break;
						case 4:
							unit = 'pps';
							break;
						default:
							unit = '个';
					}
					return commonFormatter(value, unit);
				},
			},
		},
		legend: LEGEND,
		series: [
			{
				name: '当前流量',
				// 不显示折线节点
				symbolSize: SYMBOLSIZE,
				itemStyle: {
					// normal: {
					// 	color: '#00FFFF', //折线图与小圆点颜色
					// 	lineStyle: {
					// 		width: 2, //线条宽度
					// 	},
					// },
				},
				// data: [200, 500, 100, 934, 400],
				data: echartsData.showThatDayFlowVariationData,
				type: 'line',
				areaStyle: {
					color: {
						type: 'liner',
						x: 0,
						y: 0,
						x2: 0,
						y2: 1,
						colorStops: [
							{
								offset: 0,
								color: colorSortGroup[0],
							},
							{
								offset: 1,
								color: 'rgba(58,77,233,0)',
							},
						],
						global: false, // 缺省为 false
					},
				},
			},
			{
				name: '昨天流量',
				// 不显示折线节点
				symbolSize: SYMBOLSIZE,
				itemStyle: {
					// normal: {
					// 	color: colors[1], //折线图与小圆点颜色
					// 	lineStyle: {
					// 		width: 2, //线条宽度
					// 	},
					// },
				},
				// data: [11, 123, 152, 342, 141],
				data: echartsData.showYesterdayFlowVariationData,
				type: 'line',
				areaStyle: {
					color: {
						type: 'liner',
						x: 0,
						y: 0,
						x2: 0,
						y2: 1,
						colorStops: [
							{
								offset: 0,
								color: colorSortGroup[1],
							},
							{
								offset: 1,
								color: 'rgba(58,77,233,0)',
							},
						],
						global: false, // 缺省为 false
					},
				},
			},
			{
				name: '上一个周期流量',
				// 不显示折线节点
				symbolSize: SYMBOLSIZE,
				itemStyle: {
					// normal: {
					// 	color: colors[2], //折线图与小圆点颜色
					// 	lineStyle: {
					// 		width: 2, //线条宽度
					// 	},
					// },
				},
				// data: [431, 234, 143, 187, 182],
				data: echartsData.showLastWeekFlowVariationData,
				type: 'line',
				areaStyle: {
					color: {
						type: 'liner',
						x: 0,
						y: 0,
						x2: 0,
						y2: 1,
						colorStops: [
							{
								offset: 0,
								color: colorSortGroup[2],
							},
							{
								offset: 1,
								color: 'rgba(58,77,233,0)',
							},
						],
						global: false, // 缺省为 false
					},
				},
			},
		],
		// dataZoom: dataZoom,
	} as ECOption,
	// 响应量变化趋势
	variationTrend: {
		color: colorSortGroup,
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross',
			},
			formatter: function (params: any) {
				// 自定义 tooltip 数据
				return formatterToolTipFn(params, '次', true);
			},
		},
		grid: { ...GRID, bottom: '12%' },
		xAxis: [
			{
				...xAxisOrYaxis.xAxis,
				data: echartsData.soAndso.timeLapseTrend,
			},
		],
		yAxis: [
			{
				type: 'value',
				position: 'left',
				alignTicks: true,
				axisLine: {
					show: false,
					lineStyle: {
						color: colorSortGroup[0],
					},
				},
				axisLabel: {
					color: '#fff',
					formatter: function (params: any) {
						// 自定义 tooltip 数据
						return commonFormatter(params, '次');
					},
				},
				// 去除背景网格线
				splitLine: {
					show: false,
				},
				// 展示y轴刻度
				axisTick: {
					alignWithLabel: false,
					show: false,
					inside: false,
				},
			},
			{
				type: 'value',
				name: '',
				position: 'left',
				alignTicks: true,
				offset: 80,
				axisLine: {
					show: false,
					lineStyle: {
						color: '#fff',
					},
				},
				axisLabel: {
					// formatter: '{value}',
					formatter: function (params: any) {
						// 自定义 tooltip 数据
						return commonFormatter(params, '次');
					},
				},
				// 去除背景网格线
				splitLine: {
					show: false,
				},
			},
			{
				type: 'value',
				position: 'right',
				alignTicks: true,
				axisLine: {
					show: false,
					lineStyle: {
						color: colorSortGroup[4],
					},
				},
				axisLabel: {
					color: '#fff',
					formatter: function (params: any) {
						// 自定义 tooltip 数据
						return toDecimalFormate2(params, 'wm');
					},
				},
				// 去除背景网格线
				splitLine: {
					show: false,
				},
			},
		],
		legend: LEGEND,
		series: [
			{
				name: '成功次数',
				type: 'bar',
				data: echartsData.soAndso.successCountData,
				// 动画时长
				// animationDuration: 3000,
				// 初始动画延迟
				// animationDelay: function (idx) {
				// 	return idx * 100;
				// },
				// animationDelay: 'cubicInOut',
			},
			{
				name: '客户端失败次数',
				type: 'bar',
				data: echartsData.soAndso.clientFailCountData,
			},
			{
				name: '服务端失败次数',
				type: 'bar',
				data: echartsData.soAndso.serverFailCountData,
			},
			{
				name: '超时次数',
				type: 'bar',
				data: echartsData.soAndso.timeoutCountData,
			},
			{
				name: '平均响应耗时',
				type: 'line',
				yAxisIndex: 2,
				symbolSize: SYMBOLSIZE,
				data: echartsData.soAndso.avgServerResponseCountData,
			},
		],
		// 轮播图组件
		// dataZoom: dataZoom,
	} as ECOption,
	// 调用量变化趋势折线图
	callVariationOptions: {
		color: colorSortGroup,
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'line',
			},
			formatter: function (params: any) {
				// 自定义 tooltip 数据
				return formatterToolTipFn(params, '次');
			},
		},
		grid: { ...GRID },
		xAxis: {
			...xAxisOrYaxis.xAxis,
			data: echartsData.reqCountTrendTimeLapse,
		},
		yAxis: {
			...xAxisOrYaxis.yAxis,
			// 文本颜色
			axisLabel: {
				show: true,
				textStyle: {
					color: '#fff',
				},
				formatter: function (params: any) {
					// 自定义 tooltip 数据
					return commonFormatter(params, '次');
				},
			},
		},
		legend: LEGEND,
		series: [
			{
				name: '',
				// 不显示折线节点
				symbolSize: SYMBOLSIZE,
				itemStyle: {},
				data: echartsData.reqCountTrendTimeData,
				type: 'line',
				areaStyle: {},
			},
		],
		areaStyle: {
			color: {
				type: 'liner',
				x: 0,
				y: 0,
				x2: 0,
				y2: 1,
				colorStops: [
					{
						offset: 0,
						color: colorSortGroup[0],
					},
					{
						offset: 1,
						color: 'rgba(58,77,233,0)',
					},
				],
				global: false, // 缺省为 false
			},
		},
		// dataZoom: dataZoom,
	} as ECOption,
	// 响应耗时分布柱状图
	responseConsumingOptions: {
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow',
			},
			formatter: function (params: any) {
				// 自定义 tooltip 数据
				return formatterToolTipFn(params, '次');
			},
		},
		grid: { ...GRID },
		xAxis: [
			{
				...xAxisOrYaxis.xAxis,
				data: echartsData.responseTimeDistributionLapset,
			},
		],
		yAxis: {
			...xAxisOrYaxis.yAxis,
			// 文本颜色
			axisLabel: {
				show: true,
				textStyle: {
					color: colorSortGroup[colorSortGroup.length - 1],
				},
				formatter: function (params: any) {
					// 自定义 tooltip 数据
					return commonFormatter(params, '次');
				},
			},
		},
		color: colorSortGroup,
		series: [
			{
				name: '响应耗时分布',
				type: 'bar',
				barWidth: '15%',
				data: echartsData.responseTimeDistributionData,
			},
		],
	} as ECOption,
	ApiOrSdk: [
		{ name: '调用量', value: 0 },
		{ name: '使用方数', value: 0 },
	],
	SaasOrPaas: [
		{ name: '核心页面浏览量', value: 0 },
		{ name: '使用方数', value: 0 },
		{ name: '用户数', value: 0 },
	],
	h5: [
		{ name: '浏览量', value: 0 },
		{ name: '使用方数', value: 0 },
		{ name: '用户数', value: 0 },
	],
	ydCardBtnGroup: [
		{ id: 1, name: '比特率' },
		{ id: 2, name: '字节' },
		{ id: 3, name: '包数' },
		{ id: 4, name: '包率' },
	],
	selectOptions: [],
});
const moreDialogRef: any = ref<InstanceType<typeof MoreDialog>>();
const formOptions = reactive<FormOptionType>([
	{
		type: 'select',
		label: '',
		prop: 'abilityCode',
		selectKey: 'value',
		selectLabel: 'label',
		api: { name: 'queryAbilityServer', params: {} },
	},
	{
		type: 'date-picker',
		label: '时间范围',
		prop: 'dateRange',
		dateType: 'datetimerange',
		enableCrossDay: true,
		// shortcutsKeys: ['last1h', 'today', 'lastDay'],
		// defaulShortcutsKey: 'lastlh',
		span: 10,
	},
]);

// event
let isForm = ref(false);
async function publicValueFn() {
	// 将时间还原成当前最新时间再重新去计算，不然会出现时间持续处理的情况
	params.indexDataQuery.startTime = getDefaultLast1hDate(1);
	params.indexDataQuery.endTime = getDefaultDate();
	let res = await publicValue();
	let minutes = res.data || 5;
	isForm.value = true;
	params.indexDataQuery.endTime = calculateTimeBefore(minutes, params.indexDataQuery.endTime);
	if (params.indexDataQuery.startTime.indexOf('00:00:00') === -1) {
		params.indexDataQuery.startTime = calculateTimeBefore(minutes, params.indexDataQuery.startTime, 'last1h');
	}
}
/**
 * 表单初始化数据
 */
//  async function handlerFormInit(options: BaseOptionType) {
// 	console.log(options, 'options');
// 	await publicValueFn();
// 	initRequest();
// }
// 格式化传过来的参数
function initQuery(query: anyObj, formData: FormModelType) {
	try {
		for (let key in query) {
			if (Array.isArray(formData[key])) {
				formData[key] = [];
				if (query[key]) {
					formData[key].push(query[key]);
				}
			} else {
				formData[key] = query[key];
			}
		}
	} catch {
		for (let key in query) {
			formData[key] = query[key];
		}
	}
	if (formData.systemId) {
		formData.systemId += '';
	}
}
async function handlerFormInit() {
	// params.indexDataQuery.abilityCode = params.indexDataQuery.value;
	initQuery(route.query, params.indexDataQuery);
	sessionStorage.setItem('cacheAnalysisAbilityCode', params.indexDataQuery.abilityCode);
	initRequest();
}

const { stop, reset } = startTimer((count: number) => {
	state.ind++;
	if (state.sideData[state.ind]?.isMore) {
		state.ind = 0;
	}
	if (state.ind === state.sideData.length) {
		state.ind = 0;
	}
	if (state.sideData.length <= 1) {
		state.ind = 0;
		stop();
	}
	getAbilityServerFieldDataFn();
}, 30000);
/**
 * 获取能力列表里面的字段信息，供其他地方公共调用
 */
function getAbilityServerFieldDataFn() {
	params.indexDataQuery.invocationMode = state.sideData[state.ind].invocationModeName;
	state.smailHead.title = state.sideData[state.ind].invocationModeName;
	state.smailHead.serverList = state.sideData[state.ind].serverList;
	params.indexDataQuery.serviceCode = state.sideData[state.ind].serviceCode;
	queryDataByAbilityServerFn();
	queryDataIndicatorFnAll();
	queryDataFlowAndResponseFn();
}

function sideDataClick(item: any, ind: number) {
	if (item.isMore) {
		moreDialogRef.value.show(true);
		return;
	}
	state.ind = ind;
	// params.indexDataQuery.invocationMode = item.invocationModeName;
	// state.smailHead.title = item.invocationModeName;
	// params.indexDataQuery.serviceCode = item.serviceCode;
	getAbilityServerFieldDataFn();
	reset();
}

/**
 * 流量变化清空
 */
function flowDataAssignMentNull() {
	echartsData.showThatDayFlowVariationData.length = 0;
	echartsData.showYesterdayFlowVariationData.length = 0;
	echartsData.showLastWeekFlowVariationData.length = 0;
}

/**
 * 响应量变化清空
 */
function responseAssignMentNull() {
	echartsData.soAndso.successCountData.length = 0;
	echartsData.soAndso.clientFailCountData.length = 0;
	echartsData.soAndso.serverFailCountData.length = 0;
	echartsData.soAndso.timeoutCountData.length = 0;
	echartsData.soAndso.avgServerResponseCountData.length = 0;
}

/**
 * 流量变化趋势按扭组点击
 */
function ydCardBtnGroupClick(item: { id: number; name: string }, index: number) {
	state.ydCardBtnGroupCurrent = index;
	let propFirstIndex = '';
	let propSecondIndex = '';
	let propThirdIndex = '';

	if (Object.keys(echartsData.flowVariationData).length !== 0) {
		flowDataAssignMentNull();
		if (item.id === 1) {
			propFirstIndex = 'currentBytesTotalPerList';
			propSecondIndex = 'day1BytesTotalPerList';
			propThirdIndex = 'day7BytesTotalPerList';
		} else if (item.id === 2) {
			propFirstIndex = 'currentBytesTotalList';
			propSecondIndex = 'day1BytesTotalList';
			propThirdIndex = 'day7BytesTotalList';
		} else if (item.id === 3) {
			propFirstIndex = 'currentPackageTotalList';
			propSecondIndex = 'day1PackageTotalList';
			propThirdIndex = 'day7PackageTotalList';
		} else if (item.id === 4) {
			propFirstIndex = 'currentPackageTotalPerList';
			propSecondIndex = 'day1PackageTotalPerList';
			propThirdIndex = 'day7PackageTotalPerList';
		}
		echartsData.flowVariationData[propFirstIndex]?.forEach((item: number) => echartsData.showThatDayFlowVariationData.push(item));
		echartsData.flowVariationData[propSecondIndex]?.forEach((item: number) => echartsData.showYesterdayFlowVariationData.push(item));
		echartsData.flowVariationData[propThirdIndex]?.forEach((item: number) => echartsData.showLastWeekFlowVariationData.push(item));
	}
}
/**
 * 能力查询
 */
function queryAbilityServerFn() {
	queryAbilityServer(params.indexDataQuery).then((res: ApiResponse) => {
		state.selectOptions.length = 0;
		state.sideData.length = 0;
		if (res.data && res.data.length > 0) {
			state.abilityServerData = res.data;
			res.data.forEach((items: any) => {
				if (items.abilityCode === params.indexDataQuery.abilityCode) {
					state.sideDialogData = items.serverList;
				}
			});
			if (state.sideDialogData.length <= 1) {
				stop();
			}
			if (state.sideDialogData.length >= 20) {
				state.sideData = state.sideDialogData.slice(0, 20);
				state.sideData.push({ serviceName: '更多 >', isMore: true });
			} else {
				state.sideData = state.sideDialogData;
			}
			getAbilityServerFieldDataFn();
		} else {
			state.sideData = [];
			state.sideDialogData = [];
			stop();
		}
	});
}
/**
 * 查询能力对应的流量API指标数据
 */
function queryDataFlowFn() {
	echartsData.showTimeLapaseData.length = 0;
	state.ydCardBtnGroupCurrent = 0;
	queryDataFlow(params.indexDataQuery).then((res: ApiResponse) => {
		res.data.resLabelTimeArr?.forEach((item: string) => {
			let str = parseTime(item.substring(0, 19), '{h}:{i}');
			echartsData.showTimeLapaseData.push(str);
		});
		echartsData.flowVariationData = res.data.resFieldMap;
		echartsData.flowVariationData.currentBytesTotalPerList?.forEach((item: number) => echartsData.showThatDayFlowVariationData.push(item));
		echartsData.flowVariationData.day1BytesTotalPerList?.forEach((item: number) => echartsData.showYesterdayFlowVariationData.push(item));
		echartsData.flowVariationData.day7BytesTotalPerList?.forEach((item: number) => echartsData.showLastWeekFlowVariationData.push(item));
	});
}
/**
 * 查询能力对应的响应量趋势
 */
function queryDataResponseFn() {
	echartsData.soAndso.timeLapseTrend.length = 0;
	queryDataResponse(params.indexDataQuery).then((res: ApiResponse) => {
		res.data.resLabelTimeArr?.forEach((item: string) => {
			let str = parseTime(item.substring(0, 19), '{h}:{i}');
			echartsData.soAndso.timeLapseTrend.push(str);
		});
		res.data.resFieldMap.systemSuccessCountList?.forEach((item: number) => echartsData.soAndso.successCountData.push(item));
		res.data.resFieldMap.clientFailCountList?.forEach((item: number) => echartsData.soAndso.clientFailCountData.push(item));
		res.data.resFieldMap.serverFailCountList?.forEach((item: number) => echartsData.soAndso.serverFailCountData.push(item));
		res.data.resFieldMap.timeoutCountList?.forEach((item: number) => echartsData.soAndso.timeoutCountData.push(item));
		res.data.resFieldMap.avgServerResponseTimeList?.forEach((item: number) => echartsData.soAndso.avgServerResponseCountData.push(item));
	});
}
/**
 * 查询服务对应的使用方数
 */
function queryDataByAbilityServerFn() {
	queryDataByAbilityServer(params.indexDataQuery).then((res: ApiResponse) => {
		state.smailHead.purchaseOrderNumber = res.data.purchaseOrderNumber;
		state.smailHead.userNumbers = res.data.userNumber;
	});
}

/**
 * 查询能力对应的API指标数据
 */
function queryDataIndicatorFn(prop: string) {
	queryDataIndicator(params.indexDataQuery).then((res: ApiResponse) => {
		if (prop) {
			if (prop === 'apiOrSdkData') {
				state[prop][0].value = res.data.systemSuccessRate;
				state[prop][1].value = res.data.businessSuccessRate;
				state[prop][2].value = res.data.avgServerResponseTime;
				state[prop].length = 3;
				if (res.data.isInterruptIntervalTime === 1) {
					state[prop].push({
						label: '中断耗时',
						value: res.data.interruptIntervalTime,
						type: 4,
						color: colors[6],
						colorStart: colors[7],
						isMinutes: true,
					});
				} else if (res.data.isInterruptCount === 1) {
					state[prop].push({
						label: '中断次数',
						value: res.data.interruptCount,
						color: colors[6],
						type: 2,
						colorStart: colors[7],
						isBrowse: true,
					});
				}
				state.firstApiData = state.apiOrSdkData;
				state.smailHead.reqCount = res.data.reqCount;
			} else if (prop === 'saasOrPaasData') {
				echartsData.saasOrPaasLoginSuccessRate[0].value = res.data.loginSuccessRate;
				state[prop][0].value = res.data.systemSuccessRate;
				state[prop][1].value = res.data.avgServerResponseTime;
				state.smailHead.corePageReqCount = res.data.corePageReqCount;
				state.firstApiData = state.saasOrPaasData;
				state.smailHead.userNumber = res.data.userNumber;
			} else {
				state[prop][0].value = res.data.systemSuccessRate;
				state[prop][1].value = res.data.avgServerResponseTime;
				state.firstApiData = state.h5Data;
				state.smailHead.reqCount = res.data.reqCount;
				state.smailHead.userNumber = res.data.userNumber;
			}
			echartsData['apiSaasPieData'][0].value = res.data.timeoutCount;
			echartsData['apiSaasPieData'][1].value = res.data.systemSuccessCount;
			echartsData['apiSaasPieData'][2].value = res.data.clientFailCount;
			echartsData['apiSaasPieData'][3].value = res.data.serverFailCount;
		}
	});
}
function queryDataIndicatorFnAll() {
	let propName = '';
	if (mode.value === 'ApiOrSdk') {
		echartsData.callVariationTitle = '调用量变化趋势';
		state.callVariationOptions.series[0].name = '调用量变化趋势';
		propName = 'apiOrSdkData';
	} else if (mode.value === 'SaasOrPaas') {
		echartsData.callVariationTitle = '核心页面浏览量变化趋势';
		state.callVariationOptions.series[0].name = '核心页面浏览量变化趋势';
		propName = 'saasOrPaasData';
	} else {
		echartsData.callVariationTitle = '浏览量变化趋势';
		state.callVariationOptions.series[0].name = '浏览量变化趋势';
		propName = 'h5Data';
	}
	queryDataIndicatorFn(propName);
}
/**
 * 查询服务对应的API调用量变化趋势
 */
function queryDataReqCountTrendFn() {
	echartsData.reqCountTrendTimeLapse.length = 0;
	echartsData.reqCountTrendTimeData.length = 0;
	queryDataReqCountTrend(params.indexDataQuery).then((res: ApiResponse) => {
		res.data.resLabelTimeArr?.forEach((item: string) => {
			let str = parseTime(item.substring(0, 19), '{h}:{i}');
			echartsData.reqCountTrendTimeLapse.push(str);
		});
		if (mode.value === 'SaasOrPaas') {
			res.data.resFieldMap.corePageReqCountList?.forEach((item: number) => echartsData.reqCountTrendTimeData.push(item));
			return;
		}
		res.data.resFieldMap.reqCountList?.forEach((item: number) => echartsData.reqCountTrendTimeData.push(item));
	});
}

/**
 * 响应耗时分布
 */
function queryDataResponseTimeDistributionFn() {
	echartsData.responseTimeDistributionLapset.length = 0;
	echartsData.responseTimeDistributionData.length = 0;
	queryDataResponseTimeDistribution(params.indexDataQuery).then((res: ApiResponse) => {
		Object.keys(res.data).forEach((key: string) => echartsData.responseTimeDistributionLapset.push(key));
		Object.values(res.data).forEach((val: any) => echartsData.responseTimeDistributionData.push(val));
	});
}
/**
 * 服务调用详情
 */
function serverRequestDetailsClick() {
	router.push({
		path: '/middle-monitor/ability-service-analysis/details',
		query: {
			abilityCode: params.indexDataQuery.abilityCode,
			serviceCode: params.indexDataQuery.serviceCode,
			invocationMode: mode.value,
			startTime: params.indexDataQuery.startTime,
			endTime: params.indexDataQuery.endTime,
		},
	});
}

// emit
/**
 * 搜索
 */
function handleSearchClick(data: any) {
	initRequest();
}

function handlerMoreClick(item: any, ind: number) {
	if (ind < 20) {
		state.ind = ind;
	} else {
		if (state.sideData.length === 22) {
			state.sideData.splice(20, 1, item);
		} else {
			state.sideData.splice(20, 0, item);
		}
		state.ind = 20;
	}
	getAbilityServerFieldDataFn();
	reset();
}

/**
 * 下拉框change
 */
function handlerSelectChange(options: BaseOptionType, value: any) {
	console.log(options, value, '下拉框change');
	if (options.type === 'select') {
		params.indexDataQuery.abilityCode = value;
	}
	state.ind = 0;
	initRequest();
	reset();
}

function queryDataFlowAndResponseFn() {
	flowDataAssignMentNull();
	responseAssignMentNull();
	queryDataFlowFn();
	queryDataReqCountTrendFn();
	queryDataResponseFn();
	queryDataResponseTimeDistributionFn();
}
async function initRequest() {
	await queryAbilityServerFn();
}
const myForm = ref();
onActivated(() => {
	isForm.value = false;
	state.ind = 0;
	publicValueFn();
	let res = sessionStorage.getItem('cacheAnalysisAbilityCode');
	setTimeout(() => {
		if (res !== sessionStorage.getItem('cacheAnalysisAbilityCode')) {
			myForm.value?.setOptions('abilityCode', params.indexDataQuery);
		}
	}, 0);
	reset();
	const dom = document.querySelector('.main');
	dom?.addEventListener('mouseover', () => {
		stop();
	});
	dom?.addEventListener('mouseout', () => {
		reset();
	});
});
onBeforeUnmount(() => {
	state.ind = 0;
	stop();
});
onBeforeRouteLeave((to: any, from: any, next) => {
	next();
	stop();
});
</script>

<style scoped lang="scss">
@import '../index.scss';
@import '@/styles/variables.module.scss';
.container {
	.query-form {
		.service-call-details {
			margin-left: 20px;
			cursor: pointer;
			:deep(.el-icon) {
				background-color: $--color-cyan !important;
				border-radius: 50% !important;
				width: 28px !important;
				height: 28px !important;
				color: #000;
				vertical-align: middle;
				margin-right: 10px;
			}
		}
	}
	.content {
		display: grid;
		grid-template-columns: 254px 1fr;
		// grid-template-rows: 76px repeat(7, 1fr);
		grid-column-gap: 20px;
		grid-row-gap: 20px;
		margin-top: 20px;
		.side-data {
			grid-area: 1 / 1 / 6 / 2;
			.data {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding: 15px 0;
				text-align: center;
				cursor: pointer;
				&:hover {
					color: #2beded;
					border-radius: 5px;
					background-color: rgba($color: $--color-cyan, $alpha: 0.23);
				}
			}
			.active {
				color: #2beded;
				border-radius: 5px;
				background-color: rgba($color: $--color-cyan, $alpha: 0.23);
			}
		}
		.el-row {
			.el-col {
				margin-top: 20px;
				&:nth-child(1) {
					margin-top: 0;
				}
			}
		}
		.small-head {
			font-weight: 500;
			font-size: 20px;
			height: 76px;
			:deep(.el-card__body) {
				padding: 0 50px !important;
				display: flex;
				justify-content: space-between;
				align-items: center;
			}
			div {
				&:nth-of-type(2) {
					span {
						margin-right: 50px;
					}
				}
			}
			span {
				color: $--color-cyan;
			}
		}
		.ability-service {
			:deep(.style-split-yd-card[data-v-f4f07a87] .el-card__header) {
				display: block;
			}
			:deep(.yd-card-header) {
				display: flex !important;
				justify-content: space-between !important;
				align-items: center !important;
			}
		}
		.system-success-rate {
			div {
				&:nth-of-type(1) {
					display: flex;
					justify-content: space-between;
					align-items: center;
				}
			}
		}
		.flow-variation {
			.ydCardBtnGroupClass {
				border: 1px solid #ccc;
				padding: 5px 15px;
				cursor: pointer;
				&:nth-of-type(1) {
					border-radius: 5px 0 0 5px;
				}
				&:nth-of-type(4) {
					border-radius: 0 5px 5px 0;
				}
				&.active {
					color: #2beded;
					border-color: #2beded;
				}
			}
		}
	}
	:deep(.el-col-24) {
		&:nth-of-type(1) {
			margin-top: 0 !important;
		}
	}
}
</style>
